package main

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"sync"
)

var (
	upgrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
	clients sync.Map // 使用 sync.Map 管理 WebSocket 连接池
)

type wsClient struct {
	conn *websocket.Conn
	mu   sync.Mutex // 用于锁定该连接的写操作
}

func initWs() {
	router.GET("/", handleWebSocket)
}

func handleWebSocket(c *gin.Context) {
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println("WebSocket upgrade error:", err)
		return
	}
	defer conn.Close()

	// 将 WebSocket 连接存入连接池
	client := &wsClient{conn: conn}
	clients.Store(conn, client)

	for {
		_, _, err := conn.ReadMessage()
		if err != nil {
			log.Println("WebSocket read error:", err)
			break
		}
	}

	// 连接断开后从连接池中移除
	clients.Delete(conn)
}
